/* Copyright © 2010 LPRM
Universidade Federal do Espírito Santo - RNP-GT CWTools

This file is part of JoinUs!.

JoinUs! is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

JoinUs! is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with JoinUs!. If not, see <http://www.gnu.org/licenses/>. */
package com.isisufes.joinus.appserver;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;

public class Chat extends Servlet1 {
	/*
	create table chat (
        messageId serial primary key,
        campaignId bigint not null references campaign (idcampaign),
        senderId bigint not null references profile (idprofile),
        dateSent timestamp not null,
        messageBody varchar(200) not null,
        constraint chat_index unique (campaignId, dateSent)
	) without oids;
	 */

	private static final long serialVersionUID = 1L;
	private PreparedStatement sql_update;
	private PreparedStatement sql_insert;
	private PreparedStatement sql_init;
	private PreparedStatement sql_update_new;
	private final int NUM_MENSAGENS_INICIAIS = 10;
	
	@Override
	protected void initStmt() {
		sql_init = DBConn.stmt("SELECT A.* FROM (SELECT A.dateSent, B.login AS senderName, A.messageBody FROM chat A INNER JOIN profile B ON B.idprofile = A.senderId WHERE A.campaignId = ? ORDER BY A.dateSent DESC LIMIT " + NUM_MENSAGENS_INICIAIS + ") A ORDER BY dateSent;");
		sql_insert = DBConn.stmt("INSERT INTO chat (campaignId, dateSent, senderId, messageBody) VALUES (?, NOW(), ?, ?);");
		sql_update = DBConn.stmt("SELECT A.dateSent, B.login AS senderName, A.messageBody FROM chat A INNER JOIN profile B ON B.idprofile = A.senderId WHERE A.campaignId = ? AND dateSent > ? AND (NOW() - dateSent) < '00:05' ORDER BY dateSent;");
		sql_update_new = DBConn.stmt("SELECT A.dateSent, B.login AS senderName, A.messageBody FROM chat A INNER JOIN profile B ON B.idprofile = A.senderId WHERE A.campaignId = ? ORDER BY dateSent LIMIT " + NUM_MENSAGENS_INICIAIS + ";");
	}

	@Override
	protected String dispatch(String action) throws Exception {
		String ret = "";
		
		if("init".equals(action)){
			ret = clientInit();
		}else if("update".equals(action)){
			ret = clientUpdate();
		}else if("send".equals(action)){
			ret = sendMessage();
		}
		return ret;
	}

	private String sendMessage() {
		try{
			long campaignId = Long.parseLong(arg("campaign"));
			long userId = Long.parseLong(id);
			String msg = arg("msg");
			
			sql_insert.clearParameters();
			sql_insert.setLong(1, campaignId);
			sql_insert.setLong(2, userId);
			sql_insert.setString(3, msg);
			
			sql_insert.execute();
		}catch(Exception e){
			return "ERRO!\nErro no cadastro da mensagem enviada.\n";
		}
		
		return clientUpdate();
	}
	
	private String clientUpdate(){
		String ret;
		
		try{
			ResultSet rs;
			StringBuilder sb;
			PreparedStatement stmt;
			
			long campaignId = Long.parseLong(arg("campaign"));
			try{
				Timestamp dateLastMessage = Timestamp.valueOf(arg("fromDate"));
				stmt = sql_update;
				stmt.clearParameters();
				stmt.setLong(1, campaignId);
				stmt.setTimestamp(2, dateLastMessage);
			}catch(Exception e){
				stmt = sql_update_new;
				stmt.clearParameters();
				stmt.setLong(1, campaignId);
			}
			rs = stmt.executeQuery();
			
			sb = new StringBuilder();
			sb.append("<chatMessages>\n");
			while(rs.next()){
				Timestamp date = rs.getTimestamp(1);
				String sender = rs.getString(2);
				String msg = rs.getString(3);
				sb.append("\t<message>\n" +
						"\t\t<date>" + date.toString() + "</date>\n" +
						"\t\t<sender>" + sender + "</sender>\n" + 
						"\t\t<body>" + msg + "</body>\n" +
						"\t</message>\n"
						);
			}
			sb.append("</chatMessages>\n");
			
			ret = sb.toString();

		}catch(Exception e){
			ret = e.getMessage();
			//ret = "ERRO!\n Argumentos inválidos ou erro SQL não especificado!\n";
		}
		
		return ret;
	}

	private String clientInit() {
		String ret;

		try{
			ResultSet rs;
			StringBuilder sb;
			long campaignId = Long.parseLong(arg("campaign"));
			
			sql_init.clearParameters();
			sql_init.setLong(1, campaignId);
			rs = sql_init.executeQuery();
			
			sb = new StringBuilder();
			sb.append("<chatMessages>\n");
			while(rs.next()){
				Timestamp date = rs.getTimestamp(1);
				String sender = rs.getString(2);
				String msg = rs.getString(3);
				sb.append("\t<message>\n" +
						"\t\t<date>" + date + "</date>\n" +
						"\t\t<sender>" + sender + "</sender>\n" + 
						"\t\t<body>" + msg + "</body>\n" +
						"\t</message>\n"
						);
			}
			sb.append("</chatMessages>\n");
			
			ret = sb.toString();

		}catch(Exception e){
			ret = "ERRO!\n Argumentos inválidos ou erro SQL não especificado!\n";
		}
		
		return ret;
	}

}